import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 用户信息store
export const useUserStore = defineStore('user', () => {
  // 从本地存储读取数据
  let initialUserInfo = null
  try {
    const data = localStorage.getItem('userInfo')
    initialUserInfo = data ? JSON.parse(data) : null
  } catch (error) {
    console.error('读取用户信息失败:', error)
  }
  const userInfo = ref(initialUserInfo)
  const isLoggedIn = computed(() => !!userInfo.value)

  const setUserInfo = (info) => {
    userInfo.value = info
    // 保存到本地存储
    try {
      localStorage.setItem('userInfo', JSON.stringify(info))
    } catch (error) {
      console.error('保存用户信息失败:', error)
    }
  }

  const clearUserInfo = () => {
    userInfo.value = null
    // 清除本地存储
    try {
      localStorage.removeItem('userInfo')
    } catch (error) {
      console.error('清除用户信息失败:', error)
    }
  }

  return {
    userInfo,
    isLoggedIn,
    setUserInfo,
    clearUserInfo
  }
})

// 单词学习进度store
export const useProgressStore = defineStore('progress', () => {
  // 从本地存储读取数据
  let initialDailyProgress = {
    wordsLearned: 0,
    totalWords: 0,
    studyTime: 0
  }
  try {
    const data = localStorage.getItem('dailyProgress')
    initialDailyProgress = data ? JSON.parse(data) : initialDailyProgress
  } catch (error) {
    console.error('读取每日进度失败:', error)
  }
  const dailyProgress = ref(initialDailyProgress)

  let initialOverallProgress = {
    wordsMastered: 0,
    totalWords: 0,
    studyDays: 0
  }
  try {
    const data = localStorage.getItem('overallProgress')
    initialOverallProgress = data ? JSON.parse(data) : initialOverallProgress
  } catch (error) {
    console.error('读取总进度失败:', error)
  }
  const overallProgress = ref(initialOverallProgress)

  const updateDailyProgress = (progress) => {
    dailyProgress.value = { ...dailyProgress.value, ...progress }
    // 保存到本地存储
    try {
      localStorage.setItem('dailyProgress', JSON.stringify(dailyProgress.value))
    } catch (error) {
      console.error('保存每日进度失败:', error)
    }
  }

  const updateOverallProgress = (progress) => {
    overallProgress.value = { ...overallProgress.value, ...progress }
    // 保存到本地存储
    try {
      localStorage.setItem('overallProgress', JSON.stringify(overallProgress.value))
    } catch (error) {
      console.error('保存总进度失败:', error)
    }
  }

  return {
    dailyProgress,
    overallProgress,
    updateDailyProgress,
    updateOverallProgress
  }
})

// 配置设置store
export const useConfigStore = defineStore('config', () => {
  // 从本地存储读取数据
  let initialVoiceSettings = {
    voiceId: 'en-US-Wavenet-C',
    pitch: 0,
    speakingRate: 1.0,
    volumeGainDb: 0
  }
  try {
    const data = localStorage.getItem('voiceSettings')
    initialVoiceSettings = data ? JSON.parse(data) : initialVoiceSettings
  } catch (error) {
    console.error('读取语音设置失败:', error)
  }
  const voiceSettings = ref(initialVoiceSettings)

  let initialAppSettings = {
    theme: 'light',
    notificationEnabled: true,
    autoPlayPronunciation: true
  }
  try {
    const data = localStorage.getItem('appSettings')
    initialAppSettings = data ? JSON.parse(data) : initialAppSettings
  } catch (error) {
    console.error('读取应用设置失败:', error)
  }
  const appSettings = ref(initialAppSettings)

  const updateVoiceSettings = (settings) => {
    voiceSettings.value = { ...voiceSettings.value, ...settings }
    // 保存到本地存储
    try {
      localStorage.setItem('voiceSettings', JSON.stringify(voiceSettings.value))
    } catch (error) {
      console.error('保存语音设置失败:', error)
    }
  }

  const updateAppSettings = (settings) => {
    appSettings.value = { ...appSettings.value, ...settings }
    // 保存到本地存储
    try {
      localStorage.setItem('appSettings', JSON.stringify(appSettings.value))
    } catch (error) {
      console.error('保存应用设置失败:', error)
    }
  }

  return {
    voiceSettings,
    appSettings,
    updateVoiceSettings,
    updateAppSettings
  }
})

// 学习计划store
export const useStudyPlanStore = defineStore('studyPlan', () => {
  // 从本地存储读取数据
  let initialCurrentPlan = null
  try {
    const data = localStorage.getItem('currentPlan')
    initialCurrentPlan = data ? JSON.parse(data) : null
  } catch (error) {
    console.error('读取学习计划失败:', error)
  }
  const currentPlan = ref(initialCurrentPlan)
  
  let initialCompletedDays = []
  try {
    const data = localStorage.getItem('completedDays')
    initialCompletedDays = data ? JSON.parse(data) : []
  } catch (error) {
    console.error('读取完成天数失败:', error)
  }
  const completedDays = ref(initialCompletedDays)
  const streakCount = ref(0)

  // 初始化时计算连续天数
  if (completedDays.value.length > 0) {
    updateStreakCount()
  }

  const setCurrentPlan = (plan) => {
    currentPlan.value = plan
    // 保存到本地存储
    try {
      localStorage.setItem('currentPlan', JSON.stringify(plan))
    } catch (error) {
      console.error('保存学习计划失败:', error)
    }
  }

  const addCompletedDay = (date) => {
    if (!completedDays.value.includes(date)) {
      completedDays.value.push(date)
      // 保存到本地存储
      try {
        localStorage.setItem('completedDays', JSON.stringify(completedDays.value))
      } catch (error) {
        console.error('保存完成天数失败:', error)
      }
      // 更新连续学习天数逻辑
      updateStreakCount()
    }
  }

  const updateStreakCount = () => {
    if (completedDays.value.length === 0) {
      streakCount.value = 0
      return
    }

    // 按日期排序
    const sortedDates = [...completedDays.value].sort()
    let currentStreak = 1
    
    for (let i = sortedDates.length - 1; i > 0; i--) {
      const currentDate = new Date(sortedDates[i])
      const prevDate = new Date(sortedDates[i - 1])
      const diffTime = Math.abs(currentDate - prevDate)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      
      if (diffDays === 1) {
        currentStreak++
      } else {
        break
      }
    }
    
    streakCount.value = currentStreak
  }

  return {
    currentPlan,
    completedDays,
    streakCount,
    setCurrentPlan,
    addCompletedDay
  }
})